(ns yahoo-finance)
(require 'util 'column-table)

(def *base-table-url* "http://ichart.yahoo.com/table.csv?")

(defn make-daily-url
  [s a b c d e f]
  (str *base-table-url* "s=" s
                       "&a=" a "&b=" b "&c=" c "&d=" d "&e=" e "&f=" f
                       "&g=d&ignore=.csv"))
(defn flip
  "[[1 2] [3 4]] -> [[1 3] [2 4]]"
  [xs]
  (map (fn [i] (vec (map (fn [x] (nth x i)) xs))) (range (count (first xs)))))

(defn daily-price-history
  ([symbol from-date to-date]
     (let [arr0 (.split from-date "\\.")
           arr1 (.split to-date "\\.")
           a (inc (Integer/parseInt (second arr0)))
           b (last arr0)
           c (first arr0)
           d (inc (Integer/parseInt (second arr1)))
           e (last arr1)
           f (first arr1)
           url (make-daily-url symbol a b c d e f)
           lines (util/fetch-url url)
           col-names (vec (.split (first lines) ","))
           cols (flip (map (fn [x] (vec (.split x ","))) (rest lines)))
           number-cols (map (fn [a] (vec (map (fn [x] (Double/parseDouble x)) a))) (rest cols))
           date-col (vec (map #(.replace % "-" ".") (first cols)))]
       (column-table/new col-names (vec (cons date-col number-cols)))))
  ([symbol] (daily-price-history symbol "2010.01.01" "2010.01.31"))
  ([] (daily-price-history "SPY")))
